﻿using EkStudio.com.bean.xml.RootInterface;
using EkStudio.com.bean.xml.RootInterface.Field;
using EkStudio.com.bean.xml.RootInterface.FieldEvent;
using EkStudio.com.ui.form.Auto;
using EkStudio.Com.UI.Interface;
using ScintillaNET;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace EkStudio.com.ui.form.AutoDataSource
{
    /// <summary>
    /// 数据源生成器
    /// </summary>
    public partial class AutoDataSourceForm : DevExpress.XtraEditors.XtraForm
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(AutoDataSourceForm));

        private ProjectRootPanel RootPanel = null;

        private ProjectUnitBillInterface UnitPanel = null;

        private string AutoCompleteKeywords = "select from where and";

        private DataTable WhereData = null,OutData = null;

        //private BillUiFieldsItem field = null;

        private BillFormatModule module = null;

        private List<BillFormatModule> ModList = new List<BillFormatModule>();//引用模块列表

        private List<string> ModPathList = new List<string>();//选取的字段组列表

        private List<OutFieldData> outList = null;

        private BillDataFillItem dataFill = null;//事件配置

        private ModuleFieldSelectForm SelectForm = null;

        private BillDataFillsqlSource fillSource = null;
        private BillDataFillSqlValue fillValue = null;
        private BillDataFillsqlWhere fillWhere = null;




        /// <summary>
        /// 模块数据填充数数据源创建
        /// </summary>
        /// <param name="_module"></param>
        /// <param name="hasListStyle"></param>
        public AutoDataSourceForm(BillFormatModule _module,ProjectRootPanel root, ProjectUnitBillInterface unit)
        {
            InitializeComponent();
            this.module = _module;
            this.RootPanel = root;
            this.UnitPanel = unit;
            InitForm();
        }


        private void InitForm()
        {

            #region 初始化编辑器
            this.SqlEdit.Margins[0].Width = 20;
            this.SqlEdit.Margins[2].Type = MarginType.Symbol;
            this.SqlEdit.Margins[2].Mask = Marker.MaskFolders;
            this.SqlEdit.Margins[2].Sensitive = true;
            this.SqlEdit.Margins[2].Width = 20;

            SqlEdit.Markers[Marker.Folder].Symbol = MarkerSymbol.BoxPlus;
            SqlEdit.Markers[Marker.FolderOpen].Symbol = MarkerSymbol.BoxMinus;
            SqlEdit.Markers[Marker.FolderEnd].Symbol = MarkerSymbol.BoxPlusConnected;
            SqlEdit.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner;
            SqlEdit.Markers[Marker.FolderOpenMid].Symbol = MarkerSymbol.BoxMinusConnected;
            SqlEdit.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine;
            SqlEdit.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner;

            SqlEdit.StyleResetDefault();
            SqlEdit.Styles[Style.Default].Font = "Consolas";
            SqlEdit.Styles[Style.Default].Size = 10;
            SqlEdit.StyleClearAll();


            // Configure the CPP (C#) lexer styles
            SqlEdit.Styles[Style.Cpp.Default].ForeColor = Color.Silver;
            SqlEdit.Styles[Style.Cpp.Comment].ForeColor = Color.FromArgb(0, 128, 0); // Green
            SqlEdit.Styles[Style.Cpp.CommentLine].ForeColor = Color.FromArgb(0, 128, 0); // Green
            SqlEdit.Styles[Style.Cpp.CommentLineDoc].ForeColor = Color.FromArgb(128, 128, 128); // Gray
            SqlEdit.Styles[Style.Cpp.Number].ForeColor = Color.Olive;
            SqlEdit.Styles[Style.Cpp.Word].ForeColor = Color.Blue;
            SqlEdit.Styles[Style.Cpp.Word2].ForeColor = Color.Blue;
            SqlEdit.Styles[Style.Cpp.String].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.Character].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.Verbatim].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.StringEol].BackColor = Color.Pink;
            SqlEdit.Styles[Style.Cpp.Operator].ForeColor = Color.Purple;
            SqlEdit.Styles[Style.Cpp.Preprocessor].ForeColor = Color.Maroon;
            SqlEdit.Lexer = Lexer.Cpp;

            // Set the keywords
            //SqlEdit.SetKeywords(0, "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while");
            //SqlEdit.SetKeywords(1, "bool byte char class const decimal double enum float int long sbyte short static string struct uint ulong ushort void");

            SqlEdit.SetKeywords(0, common.unit.ULabel.SQLKeys);

            #endregion

            #region 数据配置 

            WhereData = new DataTable();
            WhereData.Columns.Add("key", typeof(string));
            WhereData.Columns.Add("caption", typeof(string));
            WhereData.Columns.Add("column", typeof(string));
            WhereData.Columns.Add("etype", typeof(string));

            GridControl.DataSource = WhereData;

            OutData = new DataTable();

            OutData.Columns.Add("SourceField", typeof(string));//字段
            OutData.Columns.Add("ColumnValue", typeof(string));//输出字段标签路径
            OutData.Columns.Add("CaptionColumn", typeof(string));//输出字段显示标签
            OutData.Columns.Add("VisibleColumn", typeof(bool));//是否显示
            OutData.Columns.Add("WidthColumn", typeof(int));//宽度
            OutData.Columns.Add("DescType", typeof(string));//排序
            OutData.Columns.Add("SearchType", typeof(bool));//可否查询
            OutData.Columns.Add("column", typeof(string));//输出字段名称
            OutData.Columns.Add("languageTexts", typeof(string));//多语言标签
            OutData.Columns.Add("Trigger", typeof(bool));//是否触发事件


            OutGridControl.DataSource = OutData;


            this.SqlEdit.Enabled = !UnitPanel.ReadOnly;
            this.OutGridView.OptionsBehavior.Editable = !UnitPanel.ReadOnly;
            this.SqlWhereGrid.OptionsBehavior.Editable = !UnitPanel.ReadOnly;
            this.SubmitBtn.Enabled = !UnitPanel.ReadOnly;

            #endregion
        }


        public BillDataFillsqlSource FillSource
        {
            get
            {
                return fillSource;
            }

            set
            {
                fillSource = value;
            }
        }

        public BillDataFillSqlValue FillValue
        {
            get
            {
                return fillValue;
            }

            set
            {
                fillValue = value;
            }
        }

        public BillDataFillsqlWhere FillWhere
        {
            get
            {
                return fillWhere;
            }

            set
            {
                fillWhere = value;
            }
        }

        /// <summary>
        /// 事件填充
        /// </summary>
        public void SetSelectDataFill(BillDataFillItem fill)
        {
            this.dataFill = fill;
            ModList.Clear();
            ModPathList.Clear();
            this.WhereData.Clear();
            this.OutData.Clear();
            #region 初始化数据
            if (dataFill.SqlSource != null&& dataFill.SqlSource.Content!="")
            {
                RadioGroupList.SelectedIndex = 1;
                this.SqlEdit.Text = dataFill.SqlSource.Content;
                //加载条件设置
                if (dataFill.SqlWhere != null && dataFill.SqlWhere.WhereItems != null && dataFill.SqlWhere.WhereItems.Count > 0)
                {
                    for(int i = 0; i < dataFill.SqlWhere.WhereItems.Count; i++)
                    {
                        BillDataFillsqlWhereItem item = dataFill.SqlWhere.WhereItems[i];
                        DataRow row =  WhereData.NewRow();
                        row["key"] = item.Key;
                        row["caption"] = item.Caption;
                        row["column"] = item.Column;
                        row["etype"] = item.Etype;
                        WhereData.Rows.Add(row);
                    }
                }
                //加载输出设置
                if (dataFill.SqlValue != null && dataFill.SqlValue.ValueItem != null && dataFill.SqlValue.ValueItem.Count > 0)
                {
                    for(int i = 0; i < dataFill.SqlValue.ValueItem.Count; i++)
                    {
                        BillDataFillSqlValueItem item = dataFill.SqlValue.ValueItem[i];
                        DataRow row = OutData.NewRow();
                        row["SourceField"] = item.Key;
                        row["ColumnValue"] = item.Caption;
                        row["CaptionColumn"] = item.ShowCaption;
                        row["VisibleColumn"] = item.Visible;
                        row["WidthColumn"] = item.Width;
                        row["DescType"] = item.Order;
                        row["SearchType"] = item.Search;
                        row["column"] = item.Column;
                        row["languageTexts"] = item.LanguageTexts;
                        row["Trigger"] = item.Trigger;
                        OutData.Rows.Add(row);
                    }
                }

            }
            else
            {
                RadioGroupList.SelectedIndex = 0;
                this.SqlEdit.Text = "";
            }

            #endregion
            this.SqlWhereGrid.RefreshData();
            this.OutGridView.RefreshData();
            this.InitParam();

        }


        


        private void SqlEdit_CharAdded(object sender, CharAddedEventArgs e)
        {
            // Find the word start
            var currentPos = SqlEdit.CurrentPosition;
            var wordStartPos = SqlEdit.WordStartPosition(currentPos, true);
            // Display the autocompletion list
            var lenEntered = currentPos - wordStartPos;
            if (lenEntered > 0)
            {
                SqlEdit.AutoCShow(lenEntered, AutoCompleteKeywords);
            }
        }
        /// <summary>
        /// 添加记录行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddRow_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (SqlTabControl.SelectedTabPage.Name == "WhereTabPage")
            {
                DataRow row = WhereData.NewRow();
                row["key"] = "";
                row["caption"] = "";
                row["column"] = "";
                row["etype"] = "=";
                WhereData.Rows.Add(row);
                SqlWhereGrid.RefreshData();
                SqlWhereGrid.MoveLast();
            }else if(SqlTabControl.SelectedTabPage.Name == "ValueTabPage")
            {
                DataRow row = OutData.NewRow();
                row["SourceField"] = "";
                row["ColumnValue"] = "";
                row["CaptionColumn"] = "";
                row["VisibleColumn"] = true;
                row["WidthColumn"] = 100;
                row["DescType"] = "";
                row["SearchType"] = true;
                row["column"] = "";
                row["languageTexts"] = "";
                row["Trigger"] = true;
                OutData.Rows.Add(row);
                OutGridView.RefreshData();
                OutGridView.MoveLast();
            }
        }

        /// <summary>
        /// 选择条件取值字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepositoryParamValue_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if(e.Button.Kind== DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                if (SelectForm == null) SelectForm = new ModuleFieldSelectForm();
                SelectForm.SetFormatBill(module);
                DialogResult DR = SelectForm.ShowDialog();
                if (DR == DialogResult.OK)
                {
                    BillUiFieldsItem field = SelectForm.SelectField;
                    if (field != null)
                    {
                        DataRow data = WhereData.Rows[SqlWhereGrid.FocusedRowHandle];

                        
                        data["caption"] = SelectForm.SelectPaths.Count > 0 ? SelectForm.SelectPaths[0] : "";
                        data["column"] = field.Key;
                    }
                }
                SqlWhereGrid.RefreshRow(SqlWhereGrid.FocusedRowHandle);
            }else if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                DataRow data = WhereData.Rows[SqlWhereGrid.FocusedRowHandle];
                data["caption"] = "";
                data["column"] = "";
                SqlWhereGrid.RefreshRow(SqlWhereGrid.FocusedRowHandle);
            }
        }

        /// <summary>
        /// 输出字段选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepositoryOutSelectField_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //选择输出字段
            if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                int[] row = OutGridView.GetSelectedRows();
                if (row.Length > 0)
                {
                    int RowHandle = row[0];
                    if (SelectForm == null) SelectForm = new ModuleFieldSelectForm();
                    if (this.dataFill.EventType && this.dataFill.TargetTable != "")
                    {
                        SelectForm.SetFormatBill(module, this.dataFill.TargetTable);
                    }
                    else
                    {
                        SelectForm.SetFormatBill(module);
                    }
                    
                    DialogResult DR = SelectForm.ShowDialog();
                    if (DR == DialogResult.OK)
                    {
                        BillUiFieldsItem field = SelectForm.SelectField;
                        if (field != null)
                        {
                            DataRow data = OutData.Rows[RowHandle];
                            data["ColumnValue"] = SelectForm.SelectPaths.Count>0?SelectForm.SelectPaths[0]:"";
                            data["CaptionColumn"] = field.Caption;
                            data["column"] = field.Key;
                            data["languageTexts"] = field.LanguageTexts;
                        }
                    }
                    OutGridView.RefreshRow(RowHandle);
                }
            }else if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {//清空内容
                int RowHandle = OutGridView.GetSelectedRows()[0];
                DataRow data = OutData.Rows[RowHandle];
                data["ColumnValue"] = "";
                data["CaptionColumn"] = "";
                data["column"] = "";
                data["languageTexts"] = "";
                OutGridView.RefreshRow(RowHandle);
            }
            
        }
        /// <summary>
        /// 删除记录行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteRow_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (SqlTabControl.SelectedTabPage.Name == "WhereTabPage")
            {
                SqlWhereGrid.DeleteSelectedRows();
                SqlWhereGrid.MoveLast();
            }
            else if (SqlTabControl.SelectedTabPage.Name == "ValueTabPage")
            {
                OutGridView.DeleteSelectedRows();
                OutGridView.MoveLast();
            }
        }


        #region 移动功能

        private bool isMouseDown = false;
        private Point FormLocation;     //form的location
        private Point mouseOffset;      //鼠标的按下位置

        private void ModuleFieldSelectForm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                FormLocation = this.Location;
                mouseOffset = Control.MousePosition;
            }
        }

        private void ModuleFieldSelectForm_MouseMove(object sender, MouseEventArgs e)
        {
            int _x = 0;
            int _y = 0;
            if (isMouseDown)
            {
                Point pt = Control.MousePosition;
                _x = mouseOffset.X - pt.X;
                _y = mouseOffset.Y - pt.Y;

                this.Location = new Point(FormLocation.X - _x, FormLocation.Y - _y);
            }
        }


        private void ModuleFieldSelectForm_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
        }


        private void SqlTabControl_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (SqlEdit.Text.Trim() != "")
            {
                InitParam();
            }
        }

        #endregion

        private void AutoSqlBtn_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            AutoQueryFormula AutoQForm = new AutoQueryFormula(module,RootPanel);
            DialogResult DR = AutoQForm.ShowDialog();
            if(DR == DialogResult.OK)
            {
                //sql语句
                SqlEdit.Text = AutoQForm.SqlContent;
                //条件
                DataTable DataList = AutoQForm.ReqData;
                if (DataList.Rows.Count > 0)
                {
                    WhereData.Rows.Clear();
                    foreach(DataRow Row in DataList.Rows)
                    {
                        //WhereData.Columns.Add("key", typeof(string));
                        //WhereData.Columns.Add("caption", typeof(string));
                        //WhereData.Columns.Add("column", typeof(string));
                        DataRow whRow = WhereData.NewRow();
                        whRow["key"] = Row["FieldParamKey"];
                        whRow["caption"] = Row["FieldReqCaption"];
                        whRow["column"] = Row["FieldReqValue"];
                        whRow["etype"] = "=";
                        WhereData.Rows.Add(whRow);
                    }
                    SqlWhereGrid.RefreshData();
                }
                //输出
                outList = AutoQForm.OutList;
                RepositoryLanguageList.Items.Clear();
                if (outList.Count > 0)
                {
                    foreach(OutFieldData data in outList)
                    {
                        if(data.ShortCaption != "")
                            RepositoryLanguageList.Items.Add(data.ShortCaption);
                    }
                }

                //输出字段
                //RepositoryOutFieldList
                OutData.Rows.Clear();
                DataTable outTable = AutoQForm.OutData;
                if (outTable.Rows.Count > 0)
                {
                    //OutData.Columns.Add("SourceField", typeof(string));//字段
                    //OutData.Columns.Add("ColumnValue", typeof(string));//输出字段标签路径
                    //OutData.Columns.Add("CaptionColumn", typeof(string));//输出字段显示标签
                    //OutData.Columns.Add("VisibleColumn", typeof(bool));//是否显示
                    //OutData.Columns.Add("WidthColumn", typeof(int));//宽度
                    //OutData.Columns.Add("DescType", typeof(string));//排序
                    //OutData.Columns.Add("SearchType", typeof(bool));//可否查询
                    //OutData.Columns.Add("column", typeof(string));//输出字段名称
                    //OutData.Columns.Add("languageTexts", typeof(string));//多语言标签

                    //outData.Columns.Add("ColFieldName", typeof(OutFieldData));//输出字段caption
                    //outData.Columns.Add("ColWriteField", typeof(OutFieldData));//输出到界面的字段caption
                    //outData.Columns.Add("ColVisible", typeof(bool));//是否显示
                    //outData.Columns.Add("ColFieldWidth", typeof(int));//字段宽度
                    //outData.Columns.Add("ColCommand", typeof(string));//操作命令
                    //outData.Columns.Add("ColShowSearch", typeof(bool));//是否显示与查询
                    foreach (DataRow data in outTable.Rows)
                    {
                        DataRow Row = OutData.NewRow();
                        //OutFieldData field = (OutFieldData)data["ColFieldName"];
                        //OutFieldData outField = null; //(OutFieldData)data["ColWriteField"];
                        if (data["ColFieldName"] is OutFieldData)
                        {
                            OutFieldData field = (OutFieldData)data["ColFieldName"];
                            Row["SourceField"] = field.Key;
                            Row["CaptionColumn"] = field.ShortCaption;
                            Row["languageTexts"] = field.LanguageText;
                        }
                        else
                        {
                            Row["SourceField"] = "";
                            Row["CaptionColumn"] = "";
                            Row["languageTexts"] = "";
                        }
                        if (data["ColWriteField"] is OutFieldData)
                        {
                            OutFieldData outField = (OutFieldData)data["ColWriteField"];
                            Row["ColumnValue"] = outField.Caption;
                            Row["column"] = outField.Key;
                        }
                        else
                        {
                            Row["ColumnValue"] = "";
                            Row["column"] = "";
                        }
                        Row["VisibleColumn"] = data["ColVisible"];
                        Row["WidthColumn"] = data["ColFieldWidth"];
                        Row["DescType"] = "";
                        Row["SearchType"] = data["ColShowSearch"];
                        Row["Trigger"] = true;
                        OutData.Rows.Add(Row);
                    }
                }
                OutGridView.RefreshData();
            }
           
        }


        private void InitParam()
        {
            #region 处理输出列表
            RepositoryOutFieldList.Items.Clear();
            string sql = SqlEdit.Text;
            if (sql.Length > 0)
            {
                sql = removeBracket(sql).ToLower();
                int index = sql.IndexOf("from");
                if (index != -1)
                {
                    sql = sql.Substring(0, index).Replace("select", "").Replace("\n", " ");
                    string[] keyList = sql.Split(',');
                    if (keyList.Length > 0)
                    {
                        for (int i = 0; i < keyList.Length; i++)
                        {
                            StringBuilder value = new StringBuilder();
                            string key = keyList[i].Trim();
                            int len = key.Length;
                            char ch = key[len - 1];
                            while (ch != ' ' && ch != '.' && len > 0)
                            {
                                value.Insert(0, ch);
                                len--;
                                if (len > 0) ch = key[len - 1];
                            }
                            RepositoryOutFieldList.Items.Add(value.ToString());
                        }
                    }
                }
            }
            #endregion
            #region 处理条件参数
            RepositoryParamList.Items.Clear();
            sql = SqlEdit.Text;
            int ind = sql.IndexOf(":");
            while (ind > 0)
            {
                int begin = ind;
                int end = -1;
                StringBuilder value = new StringBuilder();

                for (int i = begin + 1; i < sql.Length; i++)
                {
                    if (!char.IsLetter(sql[i]) && sql[i] != '_')//非字母
                    {
                        end = i;
                        break;
                    }
                }
                if (end == -1)
                {
                    string str = sql.Substring(begin + 1).Trim();
                    RepositoryParamList.Items.Add(str);
                    value.Append(sql.Substring(0, begin)).Append(" ");
                }
                else
                {
                    //"sssdsdfsdfsdfsdf"
                    int width = end - begin - 1;
                    string str = sql.Substring(begin + 1, width);
                    //logger.Info(string.Format("开始位置{0},结束位置[{1}],长度{2},字符[{3},取值[{4}]]",begin+1,end,width,sql,str));
                    
                    RepositoryParamList.Items.Add(str);
                    value.Append(sql.Substring(0, begin)).Append(" ");
                    value.Append(sql.Substring(end + 1));
                }
                sql = value.ToString();
                ind = sql.IndexOf(":");
            }
            #endregion
        }
        /// <summary>
        /// 记录上移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MoveUp_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (SqlTabControl.SelectedTabPage.Name == "ValueTabPage")
            {
                int CHandleIndex = OutGridView.FocusedRowHandle;
                if (CHandleIndex > 0)
                {
                    DataRow row = OutData.Rows[CHandleIndex];

                    //OutData.Columns.Add("SourceField", typeof(string));//字段
                    //OutData.Columns.Add("ColumnValue", typeof(string));//输出字段标签路径
                    //OutData.Columns.Add("CaptionColumn", typeof(string));//输出字段显示标签
                    //OutData.Columns.Add("VisibleColumn", typeof(bool));//是否显示
                    //OutData.Columns.Add("WidthColumn", typeof(int));//宽度
                    //OutData.Columns.Add("DescType", typeof(string));//排序
                    //OutData.Columns.Add("SearchType", typeof(bool));//可否查询
                    //OutData.Columns.Add("column", typeof(string));//输出字段名称
                    //OutData.Columns.Add("languageTexts", typeof(string));//多语言标签
                    //保存当前行记录
                    BillDataFillSqlValueItem it = new BillDataFillSqlValueItem();
                    it.Key = (string)row["SourceField"];
                    it.Caption = (string)row["ColumnValue"];
                    it.Column = (string)row["column"];
                    it.ShowCaption = (string)row["CaptionColumn"];
                    it.Visible = (bool)row["VisibleColumn"];
                    it.Width = (int)row["WidthColumn"];
                    it.Order = (string)row["DescType"];
                    it.Search = (bool)row["SearchType"];
                    it.LanguageTexts = (string)row["languageTexts"];
                    //object val = OutGridView.GetRowCellValue(CHandleIndex, OutSearchType);
                    //MessageBox.Show(string.Format("表格值[{0},数据值[{1}]]", val.ToString(), row["SearchType"].ToString()));

                    //修改当前行为上一行记录
                    DataRow PevRow = OutData.Rows[CHandleIndex-1];
                    row["SourceField"] = PevRow["SourceField"];
                    row["ColumnValue"] = PevRow["ColumnValue"];
                    row["CaptionColumn"] = PevRow["CaptionColumn"];
                    row["VisibleColumn"] = PevRow["VisibleColumn"];
                    row["WidthColumn"] = PevRow["WidthColumn"];
                    row["DescType"] = PevRow["DescType"];
                    row["SearchType"] = PevRow["SearchType"];
                    row["column"] = PevRow["column"];
                    row["languageTexts"] = PevRow["languageTexts"];

                    //修改上一行为当前行记录
                    PevRow["SourceField"] = it.Key;
                    PevRow["ColumnValue"] = it.Caption;
                    PevRow["CaptionColumn"] = it.ShowCaption;
                    PevRow["VisibleColumn"] = it.Visible;
                    PevRow["WidthColumn"] = it.Width;
                    PevRow["DescType"] = it.Order;
                    PevRow["SearchType"] = it.Search;
                    PevRow["column"] = it.Column;
                    PevRow["languageTexts"] = it.LanguageTexts;

                    

                    OutGridView.RefreshRow(CHandleIndex - 1);
                    OutGridView.RefreshRow(CHandleIndex);
                    //选中上一行
                    OutGridView.MovePrev();
                }
            }
        }

        private void MoveDown_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (SqlTabControl.SelectedTabPage.Name == "ValueTabPage")
            {
                int CHandleIndex = OutGridView.FocusedRowHandle;
                if (CHandleIndex >= 0 && CHandleIndex < OutGridView.RowCount-1)
                {
                    DataRow row = OutData.Rows[CHandleIndex];

                    //OutData.Columns.Add("SourceField", typeof(string));//字段
                    //OutData.Columns.Add("ColumnValue", typeof(string));//输出字段标签路径
                    //OutData.Columns.Add("CaptionColumn", typeof(string));//输出字段显示标签
                    //OutData.Columns.Add("VisibleColumn", typeof(bool));//是否显示
                    //OutData.Columns.Add("WidthColumn", typeof(int));//宽度
                    //OutData.Columns.Add("DescType", typeof(string));//排序
                    //OutData.Columns.Add("SearchType", typeof(bool));//可否查询
                    //OutData.Columns.Add("column", typeof(string));//输出字段名称
                    //OutData.Columns.Add("languageTexts", typeof(string));//多语言标签
                    //保存当前行记录
                    BillDataFillSqlValueItem it = new BillDataFillSqlValueItem();
                    it.Key = (string)row["SourceField"];
                    it.Caption = (string)row["ColumnValue"];
                    it.Column = (string)row["column"];
                    it.ShowCaption = (string)row["CaptionColumn"];
                    it.Visible = (bool)row["VisibleColumn"];
                    it.Width = (int)row["WidthColumn"];
                    it.Order = (string)row["DescType"];
                    it.Search = (bool)row["SearchType"];
                    it.LanguageTexts = (string)row["languageTexts"];

                    //修改当前行为下一行记录
                    DataRow PevRow = OutData.Rows[CHandleIndex + 1];
                    row["SourceField"] = PevRow["SourceField"];
                    row["ColumnValue"] = PevRow["ColumnValue"];
                    row["CaptionColumn"] = PevRow["CaptionColumn"];
                    row["VisibleColumn"] = PevRow["VisibleColumn"];
                    row["WidthColumn"] = PevRow["WidthColumn"];
                    row["DescType"] = PevRow["DescType"];
                    row["SearchType"] = PevRow["SearchType"];
                    row["column"] = PevRow["column"];
                    row["languageTexts"] = PevRow["languageTexts"];

                    //修改下一行为当前行记录
                    PevRow["SourceField"] = it.Key;
                    PevRow["ColumnValue"] = it.Caption;
                    PevRow["CaptionColumn"] = it.ShowCaption;
                    PevRow["VisibleColumn"] = it.Visible;
                    PevRow["WidthColumn"] = it.Width;
                    PevRow["DescType"] = it.Order;
                    PevRow["SearchType"] = it.Search;
                    PevRow["column"] = it.Column;
                    PevRow["languageTexts"] = it.LanguageTexts;

                    OutGridView.RefreshRow(CHandleIndex);
                    OutGridView.RefreshRow(CHandleIndex + 1);
                    //选中下一行
                    OutGridView.MoveNext();
                }
            }
        }

        private void RadioGroupList_EditValueChanged(object sender, System.EventArgs e)
        {
            if (RadioGroupList.SelectedIndex == 0)
            {
                SqlTabControl.Visible = false;
                AutoSqlBtn.Visible = false;
                MoveUp.Visible = false;
                MoveDown.Visible = false;
                AddRow.Visible = false;
                DeleteRow.Visible = false;
            }
            else
            {
                SqlTabControl.Visible = true;
                AutoSqlBtn.Visible = true;
                MoveUp.Visible = true;
                MoveDown.Visible = true;
                AddRow.Visible = true;
                DeleteRow.Visible = true;
            }
        }

        private void SubmitBtn_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (RadioGroupList.SelectedIndex == 0)
            {
                this.FillSource = null;
                this.FillValue  = null;
                this.FillWhere  = null;
            }
            else
            {
                string content = this.SqlEdit.Text.Trim();
                if (content!="")
                {
                    this.fillSource = new BillDataFillsqlSource();
                    this.fillSource.Content = content;
                    //添加条件
                    if (SqlWhereGrid.RowCount > 0)
                    {
                        this.FillWhere = new BillDataFillsqlWhere();
                        this.FillWhere.WhereItems = new List<BillDataFillsqlWhereItem>();
                        for(int i = 0; i < WhereData.Rows.Count; i++)
                        {
                            DataRow row = WhereData.Rows[i];
                            BillDataFillsqlWhereItem item = new BillDataFillsqlWhereItem();
                            item.Key = (string)row["key"];
                            item.Caption = (string)row["caption"];
                            item.Column = (string)row["column"];
                            item.Etype = (string)row["etype"];
                            this.FillWhere.WhereItems.Add(item);
                        }
                    }
                    //添加输出
                    if (OutData.Rows.Count > 0)
                    {
                        this.FillValue = new BillDataFillSqlValue();
                        this.FillValue.ValueItem = new List<BillDataFillSqlValueItem>();
                        for(int i = 0; i < OutData.Rows.Count; i++)
                        {
                            DataRow row = OutData.Rows[i];
                            BillDataFillSqlValueItem it = new BillDataFillSqlValueItem();
                            it.Key = (string)row["SourceField"];
                            it.Caption = (string)row["ColumnValue"];//CaptionColumn
                            it.Column = (string)row["column"];
                            it.ShowCaption = (string)row["CaptionColumn"];
                            it.Visible = (bool)row["VisibleColumn"];
                            it.Width = (int)row["WidthColumn"];
                            it.Order = (string)row["DescType"];
                            it.Search = (bool)row["SearchType"];
                            it.LanguageTexts = (string)row["languageTexts"];
                            it.Trigger = (bool)row["Trigger"];
                            this.FillValue.ValueItem.Add(it);
                        }
                    }
                }
            }
        }

        private void OutGridView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if(e.Column.Name == "OutCaptionColumn")
            {
                string val = e.Value.ToString();
                if (val!=""&&this.outList!=null)
                {
                    bool look = false;
                    foreach(OutFieldData data in this.outList)
                    {
                        if(data.ShortCaption == val)
                        {
                            OutData.Rows[e.RowHandle]["languageTexts"] = data.LanguageText;
                            look = true;
                            break;
                        }
                    }
                    if(!look) OutData.Rows[e.RowHandle]["languageTexts"] = "";
                }
                else
                {
                    OutData.Rows[e.RowHandle]["languageTexts"] = "";
                }
            }
        }

        private void CancelBtn_Click(object sender, System.EventArgs e)
        {

        }
        /// <summary>
        /// 去括号
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private string removeBracket(string arg)
        {
            StringBuilder text = new StringBuilder();
            int index = arg.IndexOf("(");
            int timer = 20;
            while (index > 0 && timer>0)
            {
                int begin = index;
                int end = -1;
                int Number = 0;
                text.Clear();
                for (int i = begin+1; i < arg.Length; i++)
                {
                    char str = arg[i];
                    if (str == '(')
                    {
                        Number++;
                    }else if(str == ')')
                    {
                        if(Number>0)
                        {
                            Number--;
                        }
                        else
                        {
                            end = i;
                            break;
                        }
                    }
                }
                if(end != -1)
                {
                    text.Append(arg.Substring(0, begin)).Append(" ");
                    text.Append(arg.Substring(end + 1));
                }
                else
                {
                    text.Append(arg.Substring(0, begin));
                    text.Append(arg.Substring(begin + 1));
                }
                timer--;
                arg = text.ToString();
                index = arg.IndexOf("(");
            }

            return arg;
        }

    }
}